$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'invoice/orderinvoice/orderInvoiceRegisterList',
        datatype: "json",
        colModel: [
            { label: '订单号', name: 'orderId', index: '', key: true ,width: 120 , align:'center'},
            { label: '客户名称', name: 'memberName', index: '', width: 120 , align:'center'},
            { label: '联系人', name: 'shipName', index: '', width: 80 , align:'center'},
            { label: '联系方式', name: 'shipPhone', index: '', width: 120 , align:'center'},
            { label: '销售金额', name: 'payableAmount', index: '', width: 80 , align:'center'},
            { label: '已付金额', name: 'payed', index: '', width: 80 , align:'center'},
            { label: '付款状态', name: 'payStatus', index: '', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                    $.each(userData.payStatusEnum, function (index, module) {
                        if (module.value == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }},
            { label: '下单时间', name: 'createtime', index: '', width: 120 , align:'center'},
            { label: '已开票金额', name: 'taxMoney', index: '', width: 80 , align:'center'}
        ],
		viewrecords: true,
        height: 700,
        rowNum: 25,
		rowList : [25,50,75],
        rownumbers: true, 
        rownumWidth: 40,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });

            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            // 发票类型
            vm.e.taxTypeEnum = userData.taxTypeEnum;
        }
    });
    // 显示序号
    $("#jqGrid").jqGrid('setLabel',0, '序号', '{width:80}');
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		/* 查询字段 */
		q:{
			orderId: '',
            shipName: '',
            memberName: '',
            shipPhone: '',
            beginCreatetime: '',
            endCreatetime: '',
		},
		/* 枚举 */
		e:{
            taxTypeEnum: []
		},
		/* 发票登记展示信息  */
		invoice:{
			list: [],
			amount: 0,
            orderInvoice: {},
		}
	},
	methods: {
        /* 订单起始 */
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 订单结束 */
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
		/* 开票日期 */
        checkTaxTime: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false, onpicking:function (dp) {
				vm.invoice.orderInvoice.oiTaxTime = dp.cal.getNewDateStr();
			}});
        },
        /* 获取当前日期 */
        dateFormat:function() {
            var date = new Date();
            var year=date.getFullYear();
            var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        },
        /* 查询 */
		query: function () {
			vm.reload();
		},
		/* 登记发票 */
        registerInvoice: function () {
            var orderId = getSelectedRows();
            if(orderId == null){
                return ;
            }
            // 验证
            $.ajax({
                type: "GET",
                url: baseURL + "invoice/orderinvoice/orderInvoiceVerify",
                contentType: "application/json",
                data: {
                    'orderId': orderId.join(",")
                },
                success: function(r){
                    if(r.code == 0){
                    	vm.invoice.list = r.list;
                    	vm.invoice.amount = r.amount;
                        vm.invoice.orderInvoice.oiTaxTime = vm.dateFormat();
                        // 弹窗
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-molv',
                            title: "登记发票",
                            area: ['600px', '520px'],
                            shadeClose: false,
                            content: jQuery("#invoiceLayer"),
                            btn: ['保存','取消'],
                            btn1: function (index) {
                                // 保存发票信息
                                vm.invoice.orderInvoice.oiOrderIds = orderId.join(",");
                                $.ajax({
                                    type: "POST",
                                    url: baseURL + "invoice/orderinvoice/saveInvoice",
                                    contentType: "application/json",
                                    data: JSON.stringify(vm.invoice.orderInvoice),
                                    success: function(r){
                                        if(r.code === 0){
                                            layer.close(index);
                                            alert('操作成功', function(index){
                                                vm.reload();
                                            });
                                        }else{
                                            alert(r.msg);
                                        }
                                    }
                                });
                            }
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 多开登记 */
        registerInvoiceMuti: function () {
            var orderId = getSelectedRows();
            if(orderId == null){
                return ;
            }

            // 验证
            $.ajax({
                type: "GET",
                url: baseURL + "invoice/orderinvoice/orderInvoiceMultiVerify",
                contentType: "application/json",
                data: {
                    'orderId': orderId.join(",")
                },
                success: function(r){
                    if(r.code == 0){
                        vm.invoice.list = r.list;
                        vm.invoice.amount = r.amount;
                        vm.invoice.orderInvoice.oiTaxTime = vm.dateFormat();
                        // 弹窗
                        layer.open({
                            type: 1,
                            skin: 'layui-layer-molv',
                            title: "多开登记",
                            area: ['600px', '520px'],
                            shadeClose: false,
                            content: jQuery("#invoiceLayer"),
                            btn: ['保存','取消'],
                            btn1: function (index) {
                                // 保存发票信息
                                vm.invoice.orderInvoice.oiOrderIds = orderId.join(",");
                                $.ajax({
                                    type: "POST",
                                    url: baseURL + "invoice/orderinvoice/saveInvoiceMulti",
                                    contentType: "application/json",
                                    data: JSON.stringify(vm.invoice.orderInvoice),
                                    success: function(r){
                                        if(r.code === 0){
                                            layer.close(index);
                                            alert('操作成功', function(index){
                                                vm.reload();
                                            });
                                        }else{
                                            alert(r.msg);
                                        }
                                    }
                                });
                            }
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });

        },
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.orderInvoice = {};
		},
		update: function (event) {
			var oiId = getSelectedRow();
			if(oiId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(oiId)
		},
		saveOrUpdate: function (event) {
			var url = vm.orderInvoice.oiId == null ? "invoice/orderinvoice/save" : "invoice/orderinvoice/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.orderInvoice),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		del: function (event) {
			var oiIds = getSelectedRows();
			if(oiIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "invoice/orderinvoice/delete",
                    contentType: "application/json",
				    data: JSON.stringify(oiIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(oiId){
			$.get(baseURL + "invoice/orderinvoice/info/"+oiId, function(r){
                vm.orderInvoice = r.orderInvoice;
            });
		},
        reset: function () {
            vm.q.orderId = '';
            vm.q.shipName = '';
            vm.q.memberName = '';
            vm.q.shipPhone = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.reload();
        },
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{
                    'orderId': vm.q.orderId,
                    'memberName': vm.q.memberName,
                    'shipName': vm.q.shipName,
                    'shipPhone': vm.q.shipPhone,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime
                },
            }).trigger("reloadGrid");
		}
	}
});